<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\controller;

use app\api\service\Cashier as CashierService;
use app\common\service\order\Shipping2 as ShippingService;
use app\store\service\wxapp\Message as MessageService;
use app\store\service\wxapp\User as WxUser;
use think\facade\Db;

/**
 * 默认控制器
 * Class Index
 * @package app\api\controller
 */
class Index
{
    public function index()
    {

        // $logs=Db::name('jia_works_log')
        //        ->alias('log')
        //        ->join('jia_works w','w.works_id=log.works_id')
        //        ->field('log.*,w.model')
        //        ->select()->toArray();
        //        foreach ($logs as $key => $value) {
        //           if($value['model']==0){
        //            Db::name('jia_works_log')->where('log_id',$value['log_id'])->update(['value'=>'','unit'=>'']);
        //           }
        //        }

        //更新员工公众号openid
        // $clerks = Db::name('store_shop_clerk')->select()->toArray();

        // foreach ($clerks as $key => $value) {
        //     $unionid = Db::name('user_oauth')->where('user_id', $value['user_id'])->value('unionid');
        //     $openid  = Db::name('user_oauth_wxapp')->where('unionid', $unionid)->value('open_id');
        //     if ($openid) {

        //         Db::name('store_shop_clerk')->where('clerk_id', $value['clerk_id'])->update(['oauth_id' => $openid]);
        //     }
        // }
        // $clerks = Db::name('store_shop_manage')->select()->toArray();

        // foreach ($clerks as $key => $value) {
        //     $unionid = Db::name('user_oauth')->where('user_id', $value['user_id'])->value('unionid');
        //     $openid  = Db::name('user_oauth_wxapp')->where('unionid', $unionid)->value('open_id');
        //     if ($openid) {

        //         Db::name('store_shop_manage')->where('clerk_id', $value['clerk_id'])->update(['oauth_id' => $openid]);
        //     }
        // }

        echo '成功';

        //更新公众号用户
        // $user = Db::name('user')->where('platform', 'WXOFFICIAL')->select()->toArray();
        // foreach ($user as $key => $userInfo) {
        //     if (! empty($userInfo['mobile'])) {
        //         $data['store_id']    = $userInfo['store_id'];
        //         $data['user_id']     = $userInfo['user_id'];
        //         $data['mobile']      = $userInfo['mobile'];
        //         $data['create_time'] = time();
        //         Db::name('user_mobile_bind')
        //             ->where('user_id', $userInfo['user_id'])->insert($data);
        //     }

        // }
        echo '当前访问的index.php，请将index.html设为默认站点入口66';
    }

    //查询订单信息

    public function tradeQuery()
    {

        $outTradeNo     = '2025070354981009';
        $CashierService = new CashierService;
        $result         = $CashierService->setMethod('wechat')->setClient('MP-WEIXIN')->tradeQuery2($outTradeNo);
        $opend_id       = $result['payer']['openid'];
        var_dump($result);
        echo $result;
    }
    public function getTagUser()
    {
        //$open_id = Db::name('user_oauth_wxapp')->order('id desc')->value('open_id');
        $open_id = '';
        $WxUser  = new WxUser;
        $result  = $WxUser->getTags();

        $list = $result['tags'];

        foreach ($list as $tag) {
            $result2 = $WxUser->getTagUser($tag['id']);
            $result2 = json_decode($result2, true);
            $users   = $result2['data']['openid'];
            if (! empty($users)) {
                foreach ($users as $key => $openid) {
                    Db::name('user_oauth_wxapp')->where('open_id', $openid)->update(['tag_id' => $tag['id'], 'tag_name' => $tag['name']]);
                }
            }

        }

        echo '成功';
    }

    public function getUser()
    {
        $next_openid = Db::name('wxapp_setting')->where('key', 'next_openid')->value('values');
        $next_openid = '';
        $WxUser      = new WxUser;
        $result      = $WxUser->getUser($next_openid);

        if (isset($result['data'])) {
            // if (! empty($result['data']['next_openid'])) {
            //     $this->getUser($result['data']['next_openid']);
            // }

            $list = $result['data']['openid'];
            foreach ($list as $value) {
                $dd = Db::name('user_oauth_wxapp')->where('open_id', $value)->find();
                if (! $dd) {
                    $user['open_id']     = $value;
                    $user['create_time'] = time();
                    $user['store_id']    = 10001;
                    $insertData[]        = $user;
                }

            }
            if (! empty($insertData)) {
                Db::name('user_oauth_wxapp')->insertAll($insertData);
            }

            if (isset($result['next_openid'])) {
                Db::name('wxapp_setting')->where('key', 'next_openid')->update(['values' => $result['next_openid']]);
            }

        }

        echo '成功';
    }
    public function updateUser()
    {

        $list   = Db::name('user_oauth_wxapp')->where('unionid', '')->limit(100)->order('id desc')->select()->toArray();
        $WxUser = new WxUser;
        foreach ($list as $value) {
            $result = $WxUser->getUnionid($value['open_id']);

            if ($result && $result['unionid']) {
                Db::name('user_oauth_wxapp')->where('open_id', $value['open_id'])->update(['unionid' => $result['unionid']]);
            }

        }

        echo '成功';
    }

    public function fahuo_error()
    {
        $list = Db::name('payment_trade')
            ->where('order_type', 10)
            ->where('goods_type', 20)
            ->where('trade_state', 20)->where('is_error', 1)->where('is_send', 0)->select()->toArray();

        foreach ($list as $key => $value) {

            //确认发货

            $trade                   = [];
            $trade['trade_no']       = $value['trade_no'];
            $orderInfo['trade']      = $trade;
            $orderInfo['user_id']    = $value['user_id'];
            $orderInfo['trade_no']   = $value['trade_no'];
            $orderInfo['pay_method'] = 'wechat';
            $orderInfo['platform']   = 'MP-WEIXIN';
            $orderInfo['goods_name'] = '陪护服务';

            $completed = $orderInfo;

            // 发货信息同步微信平台
            $result = (new ShippingService)->syncMpWeixinShipping($completed, [
                // 同步至微信小程序《发货信息录入》
                'syncMpWeixinShipping' => 1,
                // 物流模式：1物流配送 3虚拟商品 4用户自提
                // 'logisticsType' => [
                //     self::DELIVERY_METHOD_MANUAL => ShippingService::DELIVERY_EXPRESS,
                //     self::DELIVERY_METHOD_NONE => ShippingService::DELIVERY_VIRTUAL
                // ][$param['deliveryMethod']],
                'logisticsType'        => 3,
                // 物流公司ID
                'expressId'            => '',
                // 物流单号
                'expressNo'            => '',
            ]);
            if ($result) {
                Db::name('payment_trade')->where('trade_id', $value['trade_id'])->update(['is_send' => 1]);
                Db::name('order')->where('order_id', $value['order_id'])->update(['is_fahuo' => 1]);
            } else {
                Db::name('order')->where('order_id', $value['order_id'])->update(['send_error' => 1]);
                Db::name('payment_trade')->where('trade_id', $value['trade_id'])->update(['is_error' => 1]);
            }
        }

    }

    public function fahuo()
    {
        $value = Db::name('payment_trade')
            ->where('order_type', 10)
            ->where('goods_type', 20)
            ->where('trade_state', 20)
            ->where('is_error', 0)->where('is_send', 0)->find();
        if ($value) {

            $CashierService = new CashierService;
            $dd             = $CashierService->setMethod('wechat')->setClient('MP-WEIXIN')->tradeQuery2($value['out_trade_no']);
          
            if (isset($dd['payer'])) {

                $opend_id = $dd['payer']['openid'];

                Db::name('payment_trade')->where('trade_id', $value['trade_id'])->update(['is_send' => 1]);

                //确认发货

                $trade             = [];
                $trade['trade_no'] = $value['trade_no'];

                $orderInfo['trade']      = $trade;
                $orderInfo['openid']     = $opend_id;
                $orderInfo['trade_no']   = $value['trade_no'];
                $orderInfo['pay_method'] = 'wechat';
                $orderInfo['platform']   = 'MP-WEIXIN';
                $orderInfo['goods_name'] = '陪护服务';

                $completed = $orderInfo;

                // 发货信息同步微信平台
                $result = (new ShippingService)->syncMpWeixinShipping($completed, [
                    // 同步至微信小程序《发货信息录入》
                    'syncMpWeixinShipping' => 1,
                    // 物流模式：1物流配送 3虚拟商品 4用户自提
                    // 'logisticsType' => [
                    //     self::DELIVERY_METHOD_MANUAL => ShippingService::DELIVERY_EXPRESS,
                    //     self::DELIVERY_METHOD_NONE => ShippingService::DELIVERY_VIRTUAL
                    // ][$param['deliveryMethod']],
                    'logisticsType'        => 3,
                    // 物流公司ID
                    'expressId'            => '',
                    // 物流单号
                    'expressNo'            => '',
                ]);

                if ($result) {

                    Db::name('order')->where('order_id', $value['order_id'])->update(['is_fahuo' => 1]);
                    echo '同步成功' . $value['trade_no'];exit;
                } else {
                    Db::name('payment_trade')->where('trade_id', $value['trade_id'])->update(['is_error' => 1]);
                    echo '同步失败' . $value['trade_no'];exit;
                }
            }

        }

        echo '没有订单';

    }

    //同步庫存

    public function dd()
    {
        // $orders = Db::name('order')->where('pay_status', 20)->where('order_status', 'in', [10, 30])->select()->toArray();
        // $ids    = array_column($orders, 'order_id');
        // $goods  = Db::name('order_goods')->where('order_id', 'in', $ids)->select()->toArray();

        // foreach ($goods as $key => $value) {
        //     Db::name('goods_sku')->where('goods_sku_id', $value['goods_sku_id'])
        //         ->where('goods_id', $value['goods_id'])
        //         ->dec('stock_num', $value['total_num'])->update();

        //     Db::name('goods')->where('goods_id', $value['goods_id'])
        //         ->inc('sales_actual', $value['total_num'])->dec('stock_total', $value['total_num'])->update();

        // }

        echo '成功';

    }

    //發送訂閱通知，护理通知

    public function sendMessage()
    {
        $logs = Db::name('jia_works_log')->where('is_send', 0)->select()->toArray();

        $ids = array_column($logs, 'log_id');
        Db::name('jia_works_log')->where('log_id', 'in', $ids)->update(['is_send' => 1]);

        foreach ($logs as $key => $data) {

            $order = Db::name('order')->where('order_no', $data['order_no'])
                ->field('extract_clerk_id,order_id,user_id,mobile,real_name')->find();

            $goodsName = Db::name('order_goods')->where('order_id', $order['order_id'])->value('goods_name');
            $clerkName = Db::name('store_shop_clerk')->where('clerk_id', $order['extract_clerk_id'])->value('real_name');

            $unionid  = Db::name('user_oauth')->where('user_id', $order['user_id'])->value('unionid');
            $opend_id = Db::name('user_oauth_wxapp')->where('unionid', $unionid)->value('open_id');
            $list[]   = [$opend_id];

            $users = Db::name('user_mobile_bind')
                ->where('mobile', $order['mobile'])->select()->toArray();
            $userIds = array_column($users, 'user_id');

            //其他绑定的用户
            $users = Db::name('user_oauth')
                ->where('oauth_type', 'WXOFFICIAL')->where('user_id', 'in', $userIds)
                ->field('oauth_id')->select()->toArray();
            $users = array_column($users, 'oauth_id');

            $lists = array_merge([$opend_id], $users);
            $lists = array_unique($lists);

            foreach ($lists as $key => $opend_id) {
                if ($opend_id) {
                    // 执行发送
                    $MessageService         = new MessageService;
                    $content['template_id'] = 'npMp42HWu2YNBvMw2gVxEcOcFt4GNDlcA8pK8IGSVCo';
                    //$content['page']        = 'pagesNew/order/runner/detail?orderId=' . $order['order_id'];
                    $content['page'] = '';
                    if ($data['value'] != '') {
                        $content['data']['thing2'] = $data['work_name'] . '(' . $data['value'] . $data['unit'] . ')';
                    } else {
                        $content['data']['thing2'] = $data['work_name'];
                    }

                    $content['data']['time3']   = Date('Y年m月d日 H:i', (int) $data['create_time']);
                    $content['data']['thing13'] = $clerkName;
                    $content['data']['thing11'] = $order['real_name'];

                    $content['data']['short_thing6'] = '已完成';

                    //暂时注释
                    $MessageService->send($opend_id, $content);
                }
            }

        }

        echo '成功';

    }

}
